from django.http import JsonResponse
from app01.utils.form.Police import PoliceModelForm_login,PoliceModelForm_add
from app01 import models
from django.views.decorators.csrf import csrf_exempt
import json
from django.utils import timezone
from django.db.models import Max
import random
from django.core.cache import cache
import json
@csrf_exempt
def Police_login(request):
    if request.method == "POST":
        form = PoliceModelForm_login(data=json.load(request.body)['data'])
        if form.is_valid():
            psy_obj = models.Police.objects.filter(**form.cleaned_data).first()
            if psy_obj:
                return JsonResponse({'status': 'true', 'essage': '登录成功'})
            else:
                return JsonResponse({'status': 'false', 'errors': form.errors})
    print("未发送post请求")
    return JsonResponse({'status': 'invalid_method'})
@csrf_exempt
def Police_add(request):
    if request.method == "POST":
        data = json.loads(request.body)
        print(data)
        
        form = PoliceModelForm_add(data=data['data'])
        if form.is_valid():
            # 获取当前表中的自增ID的最大值
            max_id = models.Police.objects.all().aggregate(Max('id'))['id__max']
            if max_id is None:
                max_id = 0
            next_id = max_id + 1
            # 生成Psychologist_id
            
            current_year = timezone.now().year
            police_id = f"S{current_year}0806{next_id}"
            # 保存表单之前设置Psychologist_id
            form.instance.police_id = police_id
            form.save()
            return JsonResponse({'status': True, 'message': '注册成功','id':police_id})
        return JsonResponse({'status': False, 'message': '该用户名已经存在'})
    
    elif request.method =="GET":
            verification_code = ''.join(random.choices('0123456789', k=6))
            
            return JsonResponse({'status':True,'message':verification_code})
        
    return JsonResponse({'status': False, 'errors': '请求发送错误'})
